<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title">
        <div style="margin-bottom: 15px; margin-top: 15px">
          <a-space style="margin-left: 13px;display:none">
            <span>行政区划：</span>
            <a-input-group compact>
              <a-cascader v-model:value="value18" style="width: 100%" :options="options1" expand-trigger="hover"
                placeholder="请选择行政区" changeOnSelect @change="onChange" />
            </a-input-group>
          </a-space>
          <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style="margin-top: 15px; margin-left: 25px">
            <span>核验来源：</span>
            <a-select ref="select" v-model:value="role_type" style="width: 120px">
              <a-select-option value="4">乡镇</a-select-option>
              <a-select-option value="3">区级</a-select-option>
              <a-select-option value="2">市级</a-select-option>
            </a-select>
          </a-space>
          <a-space style=" margin-top: 15px; margin-left: 15px">
            <span>关键字：</span>
            <a-input v-model:value="txtKeyWord" placeholder="请输入关键字进行查询" style="width: 256px; margin-top: -10px" />
          </a-space>
          <a-space style="margin-top: 15px; margin-left: 15px">
            <a-form-item name="cs">
              <a-checkbox v-model:checked="checkAll" v-model:value="checkValue" @change="onCheckAllChange">
                全部
              </a-checkbox></a-form-item>
          </a-space>
          <a-space style="margin-top: 15px; ">
            <a-form-item name="cs">
              <a-checkbox-group v-model:value="cs" @change="handleChange">
                <a-checkbox value="1">一层</a-checkbox>
                <a-checkbox value="2">二层</a-checkbox>
                <a-checkbox value="3">三层</a-checkbox>
                <a-checkbox value="4">三层及以上</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </a-space>

          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <space style="float: right; margin-right: 10px;margin-top: 15px;">
            <a-button type="primary" @click="handleExport"> 导出统计表</a-button>
          </space>
        </div>
      </div>
      <a-table :dataSource="tableData" :columns="displayColumns" :pagination="false"
        :scroll="{ x: 1500, y: tableHeight }" bordered :loading="loading">
        <!-- vue3 中的写法 -->
        <template #headerCell="{ column }">
          <template v-if="column.key == 'xzq'">
            <Tooltip placement="top">
              <template #title>
                <span>区县名称</span>
              </template>
              <span>区县名称 </span>
            </Tooltip>
          </template>

          <template v-if="column.key == 'zcount'">
            <Tooltip placement="top">
              <template #title>
                <span>房屋总数（栋）</span>
              </template>
              <span> 房屋总数（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'hccount'">
            <Tooltip placement="top">
              <template #title>
                <span>核查数量（栋）</span>
              </template>
              <span> 核查数量（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcl'">
            <Tooltip placement="top">
              <template #title>
                <span>核查率</span>
              </template>
              <span> 核查率 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'yhcount'">
            <Tooltip placement="top">
              <template #title>
                <span>隐患数量（个）</span>
              </template>
              <span> 隐患数量（个） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zgcount'">
            <Tooltip placement="top">
              <template #title>
                <span>整改数量（个）</span>
              </template>
              <span> 整改数量（个） </span>
            </Tooltip>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import moment from 'moment';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { ref, reactive, toRefs, onMounted, onBeforeMount, computed } from 'vue';
import { getHckProgressNew, getRegion } from '/@/api/demo/system'; //统计工作进展
import { useUserStore } from '/@/store/modules/user';
import { iTableData, iTableColumns } from './types/table';
import { iParams } from './types/params';
import { useGlobSetting } from '/@/hooks/setting';
import { downloadByUrl } from '/@/utils/file/download';
import { useCheckStore, useTitleStore } from '/@/store/modules/checkStore';
const router = useRouter();
const userStore = useUserStore();
const globSetting = useGlobSetting();
let userInfo = ref<any>(null);
const visible = ref(false);
const role_type = ref<string>('4');
const txtKeyWord = ref<string>(''); //核验人员姓名
const cs = ref<string[]>([]);; //层数
let options1 = ref<any[]>([]);
let detailTableHeight = ref<number>(0); // 表格高度
let tableHeight = ref<number>(0); // 表格高度
const dateFormat = 'YYYY-MM-DD';
const startDate = ref<any>(null); // 开始时间
const endDate = ref<any>(null); // 结束时间
const value18 = ref<string[]>([]);
const state = reactive({
  indeterminate: true,
});
const disabledFutureDate = (current) => {
  return current && current > moment().endOf('day');
};
const checkAll = ref(true);
const checkValue = ref<string>('0');
let data = reactive<{
  tableData: iTableData[];
  tableColumns: iTableColumns[];
  wscolsList: { wch: number }[];
  id: number | any;
  loading: Boolean;
  keyWorld: String;
  currentqx: string; // 当前行政区名称
  currentTitle: string;
  cityToken: string | any;
  startTime: string; // 开始时间
  endTime: string; // 结束时间
}>({
  // 表格数据
  tableData: [],
  tableColumns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 130,
    },
    {
      title: '名称',
      dataIndex: 'xzq',
      key: 'xzq',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //     let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //     let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //     let isNoZero = row[column.key] !== 0 ? true : false;
      //     return {
      //       style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //       class: 'cell-hover',
      //       onClick: async () => {
      //         getDetailData(row, "name");
      //       },
      //     };
      //   },
    },
    {
      title: '房屋总数(栋)',
      dataIndex: 'zcount',
      key: 'zcount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "total");
          },
        };
      },
    },
    {
      title: '核查数量（栋）',
      dataIndex: 'hccount',
      key: 'hccount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "hccount");
          },
        };
      },
    },
    {
      title: '未核查数量（栋）',
      dataIndex: 'whccount',
      key: 'whccount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "whccount");
          },
        };
      },
    },
    {
      title: '核查率',
      dataIndex: 'hcl',
      key: 'hcl',
      align: 'center',
      width: 170,
    },
    {
      title: '已达标数量（栋）',
      dataIndex: 'ydbcount',
      key: 'ydbcount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "ydbcount");
          },
        };
      },
    },
    {
      title: '未达标数量（栋）',
      dataIndex: 'wdbcount',
      key: 'wdbcount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "wdbcount");
          },
        };
      },
    },
    {
      title: '达标率',
      dataIndex: 'dbl',
      key: 'dbl',
      align: 'center',
      width: 130,
    },
    {
      title: '隐患数量（个）',
      dataIndex: 'yhcount',
      key: 'yhcount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "yhcount");
          },
        };
      },
    },
    {
      title: '整改数量（个）',
      dataIndex: 'zgcount',
      key: 'zgcount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "zgcount");
          },
        };
      },
    },
    {
      title: '剩余隐患数量（个）',
      dataIndex: 'syyhcount',
      key: 'syyhcount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, "sycount");
          },
        };
      },
    },
  ],
  id: null,
  loading: true,
  keyWorld: '',
  cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
  currentqx: '', // 当前行政区名称
  currentTitle: '', // 当前详情标题
  wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
});
// 表格的 ref Dom名称
let { tableData, loading, currentqx, currentTitle } = toRefs(data);
const store = useCheckStore();
const { startTime, endTime, roletype, txtKey, fooler } =
  store.formData || {};
const getCode = async () => {
  if (startTime != null && startTime != '') {
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    const sTime = moment(startTime).format('YYYY-MM-DD');
    const eTime = moment(endTime).format('YYYY-MM-DD');
    const start: any = dayjs(sTime);
    const end: any = dayjs(eTime);
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    startDate.value = start;
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    endDate.value = end;
  }
  // eslint-disable-next-line vue/no-side-effects-in-computed-properties
  txtKeyWord.value = txtKey ?? '';
  // eslint-disable-next-line vue/no-side-effects-in-computed-properties
  cs.value = fooler ?? null;
  if (fooler != null && fooler != '') {
    checkAll.value = false
  }
  // eslint-disable-next-line vue/no-side-effects-in-computed-properties
};
async function getData() {
  const { role } = userInfo.value;
  if (startDate.value == null) {
    let currentDate = moment().format('YYYY-MM-DD');
    const start: any = dayjs(currentDate);
    const end: any = dayjs(currentDate);
    startDate.value = start;
    endDate.value = end;
    getTime();
  }

  let groupname = '';
  if (role === 'City') {
    groupname = 'qxmc';
  } else if (role === 'Area') {
    groupname = 'jzmc';
  } else if (role === 'Street') {
    groupname = 'czmc';
  }
  let params = {
    groupname: groupname,
    startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
    endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    roletype: role_type.value,
    cs: cs.value + '',
    nickname: txtKeyWord.value
  };
  if (value18.value != undefined) {
    params.xzqdm = value18.value[0];
    params.towndm = value18.value[1];
    params.villagedm = value18.value[2];
  }
  console.log('@市级参数', params);
  loading.value = true;
  let res: any = await getHckProgressNew(params);
  console.log('@res--工作进入汇总表', res.items);

  if (res || res.items.length > 0) {
    loading.value = false;
    res.items.forEach((item: any, index: number) => {
      // item.name = selectClassFlyDict(item.xzqdm);
      item.index = index + 1;
    });
    // console.log('data', data);
    // 算列和
    let zcount = total(res.items, 'zcount');
    let hccount = total(res.items, 'hccount');
    // let hcl = Math.round(parseFloat((hccount / zcount) * 100)).toFixed(2) + '%';
    let hcl = (hccount / zcount * 100).toFixed(2) + '%';
    let 合计_count = '汇总';
    let yhcount = total(res.items, 'yhcount');
    let zgcount = total(res.items, 'zgcount');

    let wzgcount = total(res.items, 'syyhcount');
    let yhccount = total(res.items, 'yhccount');
    let whccount = total(res.items, 'whccount');
    let ydbcount = total(res.items, 'ydbcount');
    let wdbcount = total(res.items, 'wdbcount');
    let dbl;
    // 将变量转为数字类型，并检查有效性
    const numYdb = parseFloat(ydbcount);
    const numHc = parseFloat(hccount);

    // 验证：确保两个值都是有效数字，且分母不为0
    if (!isNaN(numYdb) && !isNaN(numHc) && numHc !== 0) {
      const ratio = (numYdb / numHc) * 100;
      dbl = ratio.toFixed(2) + '%'; // 直接保留两位小数（无需Math.round）
    } else {
      // 处理无效情况（按需自定义回退值）
      dbl = '0%'; // 或 'N/A'、'--'
    }

    let allObj = {
      xzq: 合计_count,
      zcount: zcount,
      hccount: hccount,
      hcl: hcl,
      yhcount: yhcount,
      zgcount: zgcount,
      whccount: whccount,
      syyhcount: wzgcount,
      wdbcount: wdbcount,
      ydbcount: ydbcount,
      dbl: dbl,
      yhccount: yhccount,
    };
    data.tableData = [...res.items, allObj];
  }
}
// 计算总数的方法
function total(arr: any, item: any) {
  let total = arr.reduce((pre: any, cur: any) => {
    return parseInt(pre) + parseInt(cur[item]);
  }, 0);
  return total;
}

const getDetailData = async (row: any, filed: any) => {
  // console.log('****');
  let titlename = '';
  if (filed == 'name') {
    titlename = row.xzq;
  } else if (filed === 'total') {
    titlename = row.xzq + '房屋总台账';
  } else if (filed == 'hccount') {
    titlename = row.xzq + '已核验房屋明细';
  } else if (filed == 'whccount') {
    titlename = row.xzq + '未核验房屋明细';
  } else if (filed == 'ydbcount') {
    titlename = row.xzq + '已达标房屋明细';
  } else if (filed == 'wdbcount') {
    titlename = row.xzq + '未达标房屋明细';
  } else if (filed == 'yhcount') {
    titlename = row.xzq + '有隐患房屋明细';
  } else if (filed == 'zgcount') {
    titlename = row.xzq + '已整改隐患房屋明细';
  } else if (filed == 'sycount') {
    titlename = row.xzq + '未整改隐患房屋明细';
  }

  let params = {
    xzqdm: row.xzqdm,
    startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
    endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    roletype: role_type.value,
    fooler: cs.value,
    category: filed,
    txtKey: txtKeyWord.value,
    currentTitle: titlename,
  };
  const store = useCheckStore();
  store.setData(params); // 存入Pinia

  router.push({
    path: 'VerifyStatisticalDetails/mxdetail',
  });
};
function handleExport() {
  const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
  const tk = userStore.getToken;
  let xzqdm = '';
  let towndm = '';
  let villagedmdm = '';
  if (value18.value[0] != undefined) {
    xzqdm = value18.value[0];
  }
  if (value18.value[1] != undefined) {
    towndm = value18.value[1];
  }
  if (value18.value[2] != undefined) {
    villagedmdm = value18.value[2];
  }
  getTime();
  downloadByUrl({
    url:
      uriBase +
      '/hc/evolvestatic/ExportExcel?access_token=' +
      tk +
      '&yhly=' +
      role_type.value +
      '&xzqdm=' +
      xzqdm +
      '&nickname=' +
      txtKeyWord.value +
      '&cs=' +
      cs.value + '' +
      '&towndm=' +
      towndm +
      '&villagedm=' +
      villagedmdm +
      '&startTime=' +
      startDate.value.format('YYYY-MM-DD') +
      '&endTime=' +
      endDate.value.format('YYYY-MM-DD'),
    target: '_blank',
  });
}
function getTime() {
  data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
  data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
  console.log('@查询参数 -- 开始时间', data.startTime);
  console.log('@查询参数 -- 结束时间', data.endTime);
}
function getUserInfo() {
  const userStore = useUserStore();
  userInfo.value = userStore?.getUserInfo;
}

function searchBtn() {
  getTime();
  data.loading = true;

  getData();
}
// 当"全部"复选框状态变化时
const onCheckAllChange = (e) => {
  if (e.target.checked) {
    // 如果选中了"全部"，清空其他所有选择
    cs.value = [];
  }
};
const handleChange = (checkedValues) => {
  console.log('当前选中的楼层:', checkedValues);
  checkAll.value = false;
  // 处理"全部"选项的特殊逻辑
  if (checkedValues.includes('0')) {
    // 如果选择了"全部"，则只保留"全部"选项
    cs.value = ['0'];
  }
  fetchDataWithCsFilter(cs.value)
};
const fetchDataWithCsFilter = (values) => {
  // 构建查询条件
  let condition = '';
  if (!values.includes('0') && values.length > 0) {
    condition = `${values.join(',')}`;
    if (!cs.value.concat(condition)) {
      cs.value.push(condition)
    }
  }

  // 调用API或执行查询
  console.log('查询条件:', condition);
};

async function getRegionData() {
  let res: any = await getRegion();
  options1.value = res;
}

function onChange(value) {
  value18.value = value;
}
const displayColumns = computed(() => {
  const { role } = userInfo.value;
  let arr: any[] = [];
  if (role === 'City') {
    // qx
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
    return arr;
  } else if (role === 'Area') {
    // jz
    arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
    return arr;
  } else if (role === 'Street') {
    // cun
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
    console.log('@Aarr', arr);
    return arr;
  } else {
    return data.tableColumns;
  }
});
const getTableHeight = () => {
  setTimeout(() => {
    detailTableHeight.value = window.innerHeight;
    tableHeight.value = window.innerHeight;
  });
};
onBeforeMount(() => {
  getUserInfo();
});
onMounted(() => {
  console.log('******工作进展统计初始化******');
  getRegionData();
  // getCode();
  getData();
  getTableHeight();
  // getTableData();
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
#map {
  height: calc(100vh - 140px);
}

.x-houseMng-search {
  z-index: 100;
  margin: 6px;
  position: absolute;
}

.root-house-mng-main {
  margin: 6px;
}

.x-village-tabs {
  width: 60vw;
  margin-top: 6px;
  margin-left: 40px;

  :deep(.ant-form) {
    margin-top: 6px;
  }
}
</style>
<style>
.ant-form-item {
  margin-bottom: 15px !important;
}
</style>
